package com.czl.module_storehouse.activity.managegoods.home;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.core.widget.PopupWindowCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.czl.base.config.AppConstants;
import com.czl.base.data.bean.tengyun.CategoryBean;
import com.czl.base.data.bean.tengyun.SortBean;
import com.czl.module_base.activity.BaseRecyclerViewActivity;
import com.czl.module_base.adapter.CategoryAdapter;
import com.czl.module_base.adapter.ListTree;
import com.czl.module_base.adapter.ListTreeAdapter;
import com.czl.module_base.bean.ListBean;
import com.czl.module_base.http.HttpResponse;
import com.czl.module_base.mvp.presenter.InjectPresenter;
import com.czl.module_base.mvp.view.SimpleView;
import com.czl.module_base.utils.PopWindowUtils;
import com.czl.module_storehouse.R;
import com.czl.module_storehouse.activity.managegoods.add.GoodsAddActivity;
import com.czl.module_storehouse.adapter.ManageHomeAdapter;
import com.czl.module_storehouse.databinding.HeaderManageHomeBinding;
import com.czl.module_storehouse.event.DirectAddGoodsEvent;
import com.czl.module_storehouse.event.SortEvent;
import com.czl.module_storehouse.mvp.presenter.CategoryPresenter;
import com.czl.module_storehouse.mvp.presenter.SortPresenter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xubin
 */
@Route(path = AppConstants.Router.Service.F_SERVICE_MANAGE_HOME)
public class ManageHomeActivity extends BaseRecyclerViewActivity<HeaderManageHomeBinding> implements SimpleView {
    private static final int ITEM_MAX_COUNT = 8;
    protected final List<Integer> ids = new ArrayList<>();
    private ManageHomeAdapter mAdapter;
    private List<CategoryBean> mCategoryBeanList;
    private SortBean mSelectSortBean;
    private int mSelectPosition;
    protected Boolean mPasteCode;
    protected Integer mPriceInfo;
    @InjectPresenter
    SortPresenter mSortPresenter;
    @InjectPresenter
    CategoryPresenter mCategoryPresenter;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SortEvent event) {
        if (event.isEdit() && event.getSortBean() != null) {
            mAdapter.setData(mSelectPosition, event.getSortBean());
        } else {
            onReload();
        }
    }

    public SortPresenter getSortPresenter() {
        return mSortPresenter;
    }

    public CategoryPresenter getCategoryPresenter() {
        return mCategoryPresenter;
    }

    @Override
    protected HeaderManageHomeBinding getChildBinding(LayoutInflater layoutInflater, FrameLayout containerTop) {
        return HeaderManageHomeBinding.inflate(layoutInflater, containerTop, true);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mToolBinding.toolbarContentTitle.setText("物品管理");
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mToolBinding.toolbarRightImg.setVisibility(View.GONE);
        mToolBinding.toolbarRightImg.setBackgroundResource(R.drawable.ic_more_horiz_black_24dp);
        mToolBinding.toolbarRightText.setVisibility(View.VISIBLE);
        mToolBinding.toolbarRightText.setText("删除");
        mToolBinding.toolbarRightText.setTextColor(ContextCompat.getColor(getContext(), R.color.color_25A468));

        mAdapter = new ManageHomeAdapter(R.layout.item_select_goods_manager, new ArrayList<>());
        binding.recyclerView.setAdapter(getAdapter());
        initListener();
    }

    protected BaseQuickAdapter<SortBean, ?> getAdapter() {
        return mAdapter;
    }

    private void showMenu() {
        View view = View.inflate(getContext(), R.layout.menu_add_inventory, null);
        TextView textView = view.findViewById(R.id.tv_menu_title);
        textView.setText("删除");
        PopupWindow popupWindow = new PopupWindow(getContext());
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setContentView(view);
        popupWindow.setFocusable(true);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        PopupWindowCompat.showAsDropDown(popupWindow, mToolBinding.toolbarRightImg, 20, 0, Gravity.END);
        textView.setOnClickListener(v -> {
            //编辑
            popupWindow.dismiss();
            mToolBinding.toolbarRightImg.setVisibility(View.GONE);
            mAdapter.setEdit(!mAdapter.isEdit());
            setRightTitle(mAdapter.isEdit());
        });
    }

    private void setRightTitle(boolean edit) {
        if (edit) {
            mToolBinding.toolbarRightText.setText("取消");
        } else {
            mToolBinding.toolbarRightText.setText("删除");
        }
        mToolBinding.toolbarRightText.setTextSize(15);
        mToolBinding.toolbarRightText.setCompoundDrawables(null, null, null, null);
        mToolBinding.toolbarRightText.setVisibility(View.VISIBLE);
    }

    protected void initListener() {
        mToolBinding.toolbarRightImg.setOnClickListener(v -> showMenu());
        mToolBinding.toolbarRightText.setOnClickListener(v -> {
            mToolBinding.toolbarRightImg.setVisibility(View.GONE);
            mToolBinding.toolbarRightText.setVisibility(View.VISIBLE);
            mAdapter.setEdit(!mAdapter.isEdit());
            setRightTitle(mAdapter.isEdit());
        });
        mChildBinding.etSearch.setAfterCloseFocus(true);
        mChildBinding.etSearch.setOnSearchListener(s -> searchData());
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> switchItem(view, position));
        mChildBinding.layoutSelected.llCommonAdd.setOnClickListener(v -> {
            EventBus.getDefault().postSticky(new DirectAddGoodsEvent());
            startActivity(new Intent(getContext(), GoodsAddActivity.class));
        });
        mChildBinding.textSelectSort.setOnClickListener(v -> getClassificationListCompany());
    }

    private void switchItem(View itemView, int position) {
        mSelectPosition = position;
        SortBean sortBean = mAdapter.getItem(position);
        if (R.id.iv_edit == itemView.getId()) {
            sortBean.setEditable(true);
            SortEvent event = new SortEvent(sortBean);
            EventBus.getDefault().postSticky(event);
            startActivity(new Intent(getContext(), GoodsAddActivity.class));
        } else if (R.id.iv_delete == itemView.getId()) {
            mSelectSortBean = sortBean;
            showDeleteDialog(sortBean.getSortId());
        }
    }

    private void showDeleteDialog(Integer sortId) {
        final Dialog dialog = new Dialog(this, R.style.Theme_Light_NoTitle_Dialog);
        View content = View.inflate(getContext(), R.layout.dialog_exit, null);

        TextView txMessage = content.findViewById(R.id.tx_message);
        txMessage.setText("您确定要删除该物品吗?");

        Button btnCon = content.findViewById(R.id.btn_confirm);
        btnCon.setOnClickListener(v -> {
            dialog.dismiss();
            deleteGoods(sortId);
        });
        Button btnCan = content.findViewById(R.id.btn_cancel);
        btnCan.setOnClickListener(v -> dialog.dismiss());
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(content);
        dialog.show();
    }

    private void deleteGoods(int sortId) {
        getSortPresenter().deleteSortInfo(sortId);
    }

    @Override
    protected void loadData() {
        super.loadData();
        String name = mChildBinding.etSearch.getText() == null ? null : mChildBinding.etSearch.getText().toString();
        mSortPresenter.getSortList(true, mPasteCode, ids, mPriceInfo, name);
    }

    @Override
    protected void loadMore() {
        super.loadMore();
        String name = mChildBinding.etSearch.getText() == null ? null : mChildBinding.etSearch.getText().toString();
        getSortPresenter().getSortList(false, mPasteCode, ids, mPriceInfo, name);
    }

    private void searchData() {
        KeyboardUtils.hideSoftInput(this);
        String name = mChildBinding.etSearch.getText() == null ? null : mChildBinding.etSearch.getText().toString();
        getSortPresenter().getSortList(true, mPasteCode, ids, mPriceInfo, name);
    }

    private void getClassificationListCompany() {
        if (mCategoryBeanList == null) {
            getCategoryPresenter().getclassificationlistCompany();
        } else {
            showSortPopup();
        }
    }

    private void showSortPopup() {
        if (mCategoryBeanList == null || mCategoryBeanList.size() == 0) {
            showToast("没有数据");
            return;
        }
        ListTree listTree = new ListTree();
        View view = View.inflate(getContext(), R.layout.common_recycler_view, null);
        RecyclerView recyclerView = view.findViewById(R.id.rv_item);
        CategoryAdapter categoryAdapter = new CategoryAdapter(listTree);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(categoryAdapter);
        categoryAdapter.addAll(mCategoryBeanList);
        int itemCount = categoryAdapter.getItemCount();
        int width = ScreenUtils.getScreenWidth() - SizeUtils.dp2px(30);
        if (itemCount > ITEM_MAX_COUNT) {
            int height = (int) (ScreenUtils.getScreenHeight() * 0.6f);
            PopWindowUtils.getInstance().createPopWindow(getContext(), view, width, height, "选择分类");
        } else {
            PopWindowUtils.getInstance().createPopWindow(getContext(), view, width, "选择分类");
        }
        PopWindowUtils.getInstance().showBasePopupWindow(binding.getRoot());
        categoryAdapter.setOnItemClickListener((ListTreeAdapter.OnItemClickListener<CategoryBean>) (categoryBean, title, pIdPath) -> {
            PopWindowUtils.getInstance().dismissPopupWindow();
            String name = categoryBean.getName();
            List<Integer> ids = null;
            if (categoryBean.getChildIds() != null) {
                ids = new ArrayList<>(categoryBean.getChildIds());
            }
            this.ids.clear();
            this.ids.addAll(ids);
            mChildBinding.textSelectSort.setText(name);
            mChildBinding.etSearch.setText("");
            mChildBinding.etSearch.clearFocus();
            getSortPresenter().getSortList(true, ids, null);
        });
    }

    @Override
    public <T> void showHttpResponse(HttpResponse<T> httpResponse) {
        super.showHttpResponse(httpResponse);
        if (CategoryPresenter.TAG_CATEGORY_LIST.equals(httpResponse.getRequestTag())) {
            mCategoryBeanList = (List<CategoryBean>) httpResponse.getData();
            showSortPopup();
        } else if (SortPresenter.TAG_SORT_DELETE.equals(httpResponse.getRequestTag())) {
            mAdapter.remove(mSelectSortBean);
        }
    }

    @Override
    public <T> void showData(T t) {
        super.showData(t);
        if (t instanceof ListBean) {
            handleResponseData(getAdapter(), getSortPresenter().getPageNo(), (ListBean<SortBean>) t);
        }
    }

}
